package com.jack.lib.net.ext

import androidx.lifecycle.coroutineScope
import com.jack.lib.core.net.*
import com.jack.lib.net.*
import io.reactivex.Observable
import kotlinx.coroutines.launch

/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 2020/7/28
 * desc   :
 */


/*fun <T, J: JBaseData<T>> JNetView.net(api: Observable<J>, loadingMode: NetLoadingMode = NetLoadingMode.DELAY, cacheMode: NetCacheStrategy = NetCacheStrategy.NOT(), dispatchMode: NetDispatchMode = NetDispatchMode.NORMAL, onNext: ((T?) -> Unit) = { }) {
    JNet.net(api, JNetParam.build {
        this.onNext = onNext
        this.loadingMode = loadingMode
        this.strategy = cacheMode
        this.dispatchMode = dispatchMode
        this.view = this@net
        this.api = api
    })
}*/

fun <T, J: JBaseData<T>> JNetView.net(api: (suspend () -> J)): IParam<T, J> {
    return JNetParam.build<T, J> {
        this.loadingMode = NetLoadingMode.DELAY
        this.strategy = NetCacheStrategy.NOT()
        this.dispatchMode = NetDispatchMode.NORMAL
        this.view = this@net
        this.ktApi = api
    }.also {
        it.job = it.view.lifecycle().coroutineScope.launchWhenCreated { JNet.networkHandler(it) }
    }.getParam()
}

suspend fun <T, J: JBaseData<T>> JNetView.netSync(api: (suspend () -> J), loadingMode: NetLoadingMode = NetLoadingMode.DELAY, cacheMode: NetCacheStrategy = NetCacheStrategy.NOT(), dispatchMode: NetDispatchMode = NetDispatchMode.NORMAL, onNext: ((T?) -> Unit) = { }): IParam<T, J> {
    return JNetParam.build<T, J> {
        this.onNext = onNext
        this.loadingMode = loadingMode
        this.strategy = cacheMode
        this.dispatchMode = dispatchMode
        this.view = this@netSync
        this.ktApi = api
    }.also {
        JNet.networkHandler(it)
    }.getParam()
}
